<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: anguolei@clcw.com.cn                                           |
// +------------------------------------------------------------------------+
//
/**
 * 车商充值
 */
namespace AuctionAppApi\Controller;

use AuctionAppApi\Service\ThriftBailService;
use AuctionCore\CarDealer\AssetCenter;
use AuctionCore\CarDealer\Dealer;
use AuctionCore\CarDealer\Recharge as Charge;
use AuctionCore\CarResource\DealerRepairPayLog;
use AuctionCore\System\AuctionException;
use Common\Lib\Lakala\Lakala;
use Think\Log;
use AuctionCore\System\SystemConf;
use AuctionCore\Common\AntNest;

class RechargeController extends BaseController
{
    public $h5_actions = array('C_RECHARGE|A_INDEX', 'C_RECHARGE|A_CREATEORDER', 'C_RECHARGE|A_RESULT');
    public $branch_id = null;
    public function __construct()
    {
        parent::__construct();
        $alipayConf = SystemConf::getConfByName("ALIPAY_CONFIG");
        $this->alipayConf = json_decode($alipayConf['value'],true);
        if(!empty($this->dealer_id)) {
            $d = new Dealer($this->dealer_id);
            $this->dealer_info = $d->detail();
            $this->branch_id = $this->dealer_info['depart_id'];
            //获取alipayconfig
            $this->alipay_user = $this->alipayConf[$this->branch_id];
        }
    }

    //加载充值页面
    public function index()
    {
        if (!$this->dealer_id) {
            AuctionException::make_throw('500001');
        }
        if (empty($this->dealer_info)) {
            AuctionException::make_throw('500012');
        }
        if ($this->dealer_info['category'] != 1) { //正式车商才可以充值
            AuctionException::make_throw('500021');
        }
        $version = I('get.version');
        $device = I("request.device_model");
        $this->assign("device_model",$device);
        $this->assign("dealer_id", $this->dealer_id);
        $this->assign("version",$version);
        $this->display();
    }

    /**
     * 获取充值选项
     */
    public function recharge(){
        $dealer_id = I('post.dealer_id/d', 0);
        $amount = I('post.money');
        $type = I('post.type');
        if ($this->dealer_info['level'] == 0) { //正式车商才可以充值
            AuctionException::make_throw('500022');
        }
        if (!$dealer_id) {
            AuctionException::make_throw('500001');
        }
        if ($amount<=0) {
            AuctionException::make_throw('500072');
        }
        if((int)$amount != $amount){
            AuctionException::make_throw('500016');
        }
        $info = $this->createOrder_v151($dealer_id,$amount);
        $option = [
            'map_app_type' => 1,
            'map_order_no' => $info['order_no'], // 业务订单号
            'map_order_title' => '充值保证金', // 订单标题
            'total_amount' => $amount, // 订单金额
            'map_notice_url' => 'http://appapi.lpaiche.com/Recharge/public_check_alipay', // 业务订单处理结果回调地址
            'map_callback_url' => 'http://appapi.lpaiche.com/Recharge/result',  //业务订单支付完毕跳转地址
            'trade_area' => 'zb',
        ];
        $ant = new AntNest();
        $result = $ant->generate($option);
        //生成支付宝请求参数
        //$alipay_request = AlipayService::apppay($info['order_no'],$info['amount'],$this->alipay_user,"保证金","保证金");
        $option = array(
            "lakala"=>array(
                "enable"=>true,
                "checked"=>true,
                //"url"=>"/Recharge/jump?orderNo=".$info['order_no']."&dealer_id=".$dealer_id,
                "url"=>isset($result['data']['trade_request_str']['LAKALA']['zb']) ? '/Recharge/jump?lakala=' . $result['data']['trade_request_str']['LAKALA']['zb'].'&orderNo='.$info['order_no'].'&dealer_id='.$dealer_id : '',
             ),
            "alipay"=> array(
                "enable"=>true,
                "pay_info"=> isset($result['data']['trade_request_str']['ALIPAY']['zb']) ? $result['data']['trade_request_str']['ALIPAY']['zb'] : '',
            ),
            "pay_amount"=>$amount,
            "order_no"=>$info['order_no'],
            "order_time"=>$info['order_time']
        );
        $this->api_200($option);
    }


    /**同步支付校验 -支付宝
     * @throws AuctionException
     */
    public function attestation(){
       
        $pay_method = I("post.pay_method");
        $pay_result  = I("post.pay_result");
        if($pay_method == 2){
            $pay_method = 'ALIPAY';
        }elseif($pay_method == 1){
            $pay_method = 'LAKALA';
        }
//        $pay_result = '{"alipay_trade_app_pay_response":{"code":"10000","msg":"Success","app_id":"2016101902241402","auth_app_id":"2016101902241402","charset":"UTF-8","timestamp":"2016-10-20 16:21:33","total_amount":"1.00","trade_no":"2016102021001004470236789021","seller_id":"2088521052578966","out_trade_no":"DA2016102016210174262"},"sign":"aTpJIQ+BLMjrVCYquUBJ9Pqe0JFg/r2s+8dG1JzFbtdZCrbemvCJzHTovyCPdgrx12gjebAsvB3TVc1oOZQ+mBAzAU2FkaJm6H6waMTEiXSWOWV94mWrvlWs90Oli0NgEd/+1DYwXk3+XL+4dCNhEHs/GltTmGKOSSLVezNB5Vs=","sign_type":"RSA"}';
        if( empty($pay_method) || empty($pay_result )){
            AuctionException::make_throw("9000000");
        }
        //获取Alipay同步结果
        $ant = new AntNest();
        $info = $ant->verify($pay_method,$pay_result);
        if(!$info){
            AuctionException::make_throw('9000001');
        }
        if($info['data']['trade_result'] == 'success'){
            $this->api_200(array('result'=>0));
        }else{
            $this->api_200(false);
        }
    }

    //支付跳转页面
    public function jump()
    {
        $device = I("request.device_model");
        $lakala = I('get.lakala', '');
        $dealer_id = I('get.dealer_id/d', 0);
        if (empty($lakala)) {
            AuctionException::make_throw('1700000');
        }
        if (!$dealer_id) {
            AuctionException::make_throw('500001');
        }
        $result = json_decode(urldecode($lakala), true);
        $this->assign("device", $device);
        $this->assign('result', $result);
        $this->display();
    }
    /**
     * 构建订单
     * @param int $dealer_id
     * @param float $amount
     * @return array|bool
     */
    private function createOrder($dealer_id, $amount)
    {
        $order_no = gen_recharge_no($dealer_id, 1); //构建订单
        $data = array(
            'dealer_id' => $dealer_id,
            'amount' => $amount,
            'order_no' => $order_no,
            'pay_type' => 1, //充值类型:保证金充值
            'third_party' => 1, //第三方:拉卡拉
        );
        $ca = new Charge($dealer_id);
        $res = $ca->create($data);
        //dump($res);
        if (!$res) {
            return false;
        }
        $order_time = date("YmdHis");
        $order_summary = I('post.order_summary');
        $la = new Lakala();
        $result = $la->create_order($order_no, $amount, $order_time, $order_summary);
        //dump($result);exit;
        return $result;
    }


    /**
     * 构建订单
     * @param int $dealer_id
     * @param float $amount
     * @return array|bool
     */
    private function createOrder_v151($dealer_id, $amount)
    {
        $order_no = gen_recharge_no($dealer_id, 1); //构建订单
        $data = array(
            'dealer_id' => $dealer_id,
            'amount' => $amount,
            'order_no' => $order_no,
            'pay_type' => 1, //充值类型:保证金充值
            //'third_party' => $pay_type, //第三方:拉卡拉
            'create_time' => date("Y-m-d H:i:s")
        );
        //查询当前车商归属分公司
        $data['branch_id'] = $this->branch_id;
        $ca = new Charge($dealer_id);
        $res = $ca->create($data);
        if (!$res) {
            return false;
        }
        $order_time = date("YmdHis");
        return array('order_time'=>$data['create_time'],'order_no'=>$order_no,'amount'=>$amount,'time'=>$order_time,'order_id'=>$res,'branch_id'=>$data['branch_id']);
    }

    //充值结果页
    public function result()
    {
        $postData = I('post.');
        $pay_status = null;

        if ($postData['retCode'] != '0000') {
            $order_no = $postData['orderId'];
            Log::record("订单 " . $order_no . "支付失败,原因: " . $postData['retMsg'], 'ERR', true);
            $pay_status = 1;
        } else {
            //前端显示结果处理
            $pay_status = 0;
        }
        $this->assign('pay_status', $pay_status);
        $this->display();
    }

    //后台处理订单
    public function background()
    {
        $postData = file_get_contents("php://input");
        //记录post数据
        Log::record($postData, 'INFO', true);
       // $postData = '{"encData":"A88307D706CA7485A614CB957D74F409075B4828F6F7CBDE2A23C6151D6BE6A752BF43E3C9D14EA3EF73CE62D7DA4EBE5877043172752FCD82153CFEE3CF890E95A18DB0E58BFB9B0779B43998635064D4CFB9FC35523EDB610396BE1B5B763CA4728898E75F96D847DF518463DA9669406A145B868FDA846D99ABC6F200293E8EF6844F3AE50B136CDF4FBFFB8BDD2E0E3AE6013D521E01708463B13353C86EEC61649D034CEEF1063BE7C0CC642366D90699C4DBD3E9D26D9D6C66A922D262DD44BD312E6A3F2AAD294AC5248F86FBA88212FF8813DAE48422B41FC91F7106075B4828F6F7CBDE3E099DB2DFDE57E90367079AF986F19F1B93B29EC44BD86169F4C974D807F9513D75EF7633963219F1CC626AED572CC2","ts":"20170223213850000724","encKey":"4E39441E7077551FADA1A86B70F7BB031D126DE863B608A0709AF70AEF57DF8094B6992A8770B33852FBD30C15EE88D48919F0A263F79DE3E943A49B44505C92C00FA0293D40FD7B9DBAA4696F5C49012845D6A8E62C30B81CCD0535E6AEC4DA1A302D3636AC17291A410DC5BBAD4955891296266B287AEA09B79CF6BE397FB0","reqType":"B0005","merId":"DOPCHN000028","mac":"0F9DF07EEA9BE29EECD2B487AF6F3B8B1DC6E54002F77F46A51A4ADB81121E7A827CD83CDB26EDD3D39CE74A721D64253FF50F388A4A39B796A33B3F383C7D27CBC558A47618021D3302B57658ED92D74348C2AADFE2E945BA5664F5FF539D85DEBCAC8594B608664A96D987D833C63EA593B82DF49BFCC2C8AE0956AFFB0292","ver":"1.0.0"}';
        if (!is_array($postData))
            $postData = json_decode($postData, true);


        $la = new Lakala();
        $res = $la->decryptAsyncData($postData);

        if ($res['status'] == 0) {
            Log::record($res['error'], 'ERR', true);
            exit;
        }

        M()->startTrans();
        $order_info = Charge::getByOrderTransactionId($res['data']['transactionId']);

        if (!empty($order_info)) {
            Log::record($res['data']['transactionId'] . "已更新过", 'ERR', true);
            exit;
        }
        //更新订单信息
        $order_no = $res['data']['merOrderId'];
        $data['pay_result'] = $res['data']['payResult'];
        $data['transaction_id'] = $res['data']['transactionId'];
        $data['deal_time'] = $res['data']['dealTime'];
        $data['order_fee'] = $res['data']['orderFee'];
        $data['remark'] = json_encode($res, JSON_UNESCAPED_UNICODE);

        if ($res['data']['payResult'] == 1) {
             $order = Charge::getByOrderNo($order_no);
             if (empty($order)) {
                Log::record("车商信息不存在", 'ERR', true);
                exit;
             }
             //收银台收款记录
             $collection_no  = genBillsNo('SK',5);
             $colle_state = AssetCenter::collection_log($collection_no,$order['amount'],5);

             $bail = new ThriftBailService();
             $bail_state = $bail->incBail($order['dealer_id'],$order['amount'],"保证金充值[" . $order_no . "]",$order_no,$order['id'],2,$colle_state);
             $res = false;

             if($bail_state->code=='000000'){
                $res = true;
             }
//           $Asset = new AssetCenter($order['dealer_id']);
//           $res = $Asset->bail_rechange($order['amount'], 2, "保证金充值[" . $order_no . "]",$order_no,$order['id'],$colle_state);
             if (!$res) {
                M()->rollback();
                Log::record("车商: [ {$order['dealer_id']} ],充值: [ {$order['amount']} ], 失败", 'ERR', true);
             }
             $this->check_minus($order['dealer_id']);
             Log::record("车商: [ {$order['dealer_id']} ],充值: [ {$order['amount']} ], 成功", 'INFO', true);

        }
        M()->commit();
        //记录充值结果
        $res = Charge::upByOrderNo($order_no, $data);

        if (!$res) {
            Log::record("update order [ {$order_no} ] recharge record faild", 'ERR', true);
        }

        Log::record("update recharge  order [ {$order_no} ]  record success", 'INFO', true);
    }

    //重新支付
    public function recharge_again()
    {
        $order_no = I('post.order_no');
        if (!$order_no) {
            AuctionException::make_throw('500073');
        }
        //获取上次订单信息
        $order = Charge::getByOrderNo($order_no);
        if (!$order) {
            AuctionException::make_throw('500073');
        }
        $res = $this->createOrder($order['dealer_id'], $order['amount']);
        if (!$res) {
            AuctionException::make_throw('500073');
        }
        $this->assign('result', $res);
        $this->display('Recharge/jump');
    }

    /**
     * 接受异步回调
     */
    public function notifyAlipay()
    {
        $option['total_amount'] = I('post.total_amount');
        $option['buyer_id']   = I('post.buyer_id');
        $option['trade_no'] = I('post.trade_no');
        $option['body'] = I('post.body');
        $option['subject'] = I('post.subject');
        $option['notify_type'] = I('post.trade_status_sync');
        $option['out_trade_no'] = I('post.out_trade_no');
        $option['trade_status'] = I('post.trade_status');
        $option['gmt_payment'] = I('post.gmt_payment');
        $option['gmt_create'] = I('post.gmt_create');
        $option['app_id'] = I('post.app_id');
        $option['seller_id'] = I('post.seller_id');
        $option['notify_id'] = I('post.notify_id');

        $sign_type = I('post.sign_type');
        $sign = I('post.sign');


//        $charge = new Charge();
//        $order_info = $charge->getByOrderNo($option['out_trade_no'],'lock');
//        $d = new Dealer($order_info['dealer_id']);
//        $dealer_info = $d->detail();
//        $this->branch_id = $dealer_info['depart_id'];
//        $this->alipay_user = $this->alipayConf[$dealer_info['depart_id']];
//        AlipayService::check_rsa($option,$sign,$this->alipay_user);

        info_log('Alipay/Asny',array("".$option['out_trade_no'].""=>$_POST));
        $this->public_check_alipay($option['out_trade_no'],$option['trade_no'],true,2);

    }

    /**
     * Alipay公用数据校验与验签
     * @param $out_trade_no
     * @param $trade_no
     * @param bool|false $isAsyn
     * @param $pay_method
     * @param array $info
     * @throws AuctionException
     */
    public function public_check_alipay(){
        $out_trade_no = I('post.order_sn', '');
        $orderAmount = I('post.order_amount');
        $trade_no = I('post.pay_sn', '');
        $payCode = I('post.pay_code', '');
        $payStatus = I('post.pay_status', '');
        $payTime = I('post.pay_time');
        $payNo = I('post.pay_no','');
        $receipt_amount = I('post.receipt_amount','');
        $ret_msg = json_encode($_POST);
        info_log('Alipay/Error',$ret_msg);
        $logData = [
            'order_sn' => $out_trade_no,
            'order_amount' => $orderAmount,
            'pay_sn' => $trade_no,
            'pay_no' => $payNo,
            'pay_code' => $payCode,
            'pay_status' => $payStatus,
            'pay_time' => $payTime,
            'create_time' => date('Y-m-d H:i:s')
        ];
        //通过返回订单号查询订单信息
        M()->startTrans();
        $charge = new Charge();
        $order_info = $charge->getByOrderNo($out_trade_no);
 	    if (empty($out_trade_no) || empty($orderAmount) || empty($trade_no)
            || empty($payCode) || empty($payTime) || empty($payStatus)
        ){
            $logData['code'] = 9000000;
            Charge::setAntTradePayLog($logData);
            AuctionException::make_throw("9000000");
        }
        //如果查询不到订单返回失败状态
        if(empty($order_info)){
            $logData['code'] = 9000003;
            Charge::setAntTradePayLog($logData);
            AuctionException::make_throw("9000003");
        }
        //判断是否已充值成功
        if($order_info['pay_result']==1){
            $logData['code'] = 9000004;
            Charge::setAntTradePayLog($logData);
            $this->api_200();
        }
        //验证参数正确定性
        if( intval($orderAmount)!= intval($order_info['amount'])){
            $logData['code'] = 9000001;
            Charge::setAntTradePayLog($logData);
            AuctionException::make_throw("9000005");
        }
        if($payStatus == 'TRADE_SUCCESS'){
            //修改订单成功状态
            $data = array(
                'third_party' => empty($payCode) ? 2 : C('PAY_METHOD.'.$payCode),
                'pay_result' => 1,
                'ret_msg' => $ret_msg,
                'order_fee'=>doubleval($orderAmount - $receipt_amount),
                'transaction_id' => $trade_no,
                'deal_time' =>  date('Y-m-d H:i:s',$payTime),
            );
            //收银台收款记录
            $collection_no  = genBillsNo('SK',5);
            $colle_state = AssetCenter::collection_log($collection_no,$order_info['amount'],5);
            $result = $charge->upByOrderNo($out_trade_no,$data);
            if($payCode == 'ALIPAY'){
                $recharge_method = 1;
            } elseif ($payCode == 'LAKALA'){
                $recharge_method = 2;
            }
            $bail = new ThriftBailService();
            $bail_state = $bail->incBail($order_info['dealer_id'],$order_info['amount'],"保证金充值[" . $out_trade_no . "]",$out_trade_no,$order_info['id'],$recharge_method,$colle_state);

            $res = false;
            if($bail_state->code=='000000'){
                $res   = true;
            }
            if (!$res || $result === false) {
                Log::record("车商: [ {$order_info['dealer_id']} ],充值: [ {$order_info['amount']} ], 失败", 'ERR', true);
                M()->rollback();
            }
            Log::record("车商: [ {$order_info['dealer_id']} ],充值: [ {$order_info['amount']} ], 成功", 'INFO', true);

        } else{
            M()->rollback();
            info_log('Alipay/Error',array('金额异常'=>$ret_msg));
            exit(json_encode(array('code'=>500,'msg'=>'订单异常')));
        }
        $logData['code'] = 200;
        Charge::setAntTradePayLog($logData);
        M()->commit();
        //检测是否有透支情况
        $this->check_minus($this->dealer_id);
        $this->api_200();
    }

    /**     * @param $dealer_id
     */
    private function check_minus($dealer_id){
        $credit_lines = SystemConf::getConfByName("REPAIR_CREDIT_LINES");
        $single_price = SystemConf::getConfByName("REPAIR_SINGL_PRICE");
        $credit_lines = $credit_lines['value'];
        $single_price = $single_price['value'];
        $d = new Dealer($dealer_id);
        $this->dealer_info = $d->detail();
        $minus_amount = $this->dealer_info['minus_amount'];
        if($minus_amount==$credit_lines && $this->dealer_info['bail_amount']>=$single_price){
            $dealer = new Dealer($dealer_id);
            $pay_log = new DealerRepairPayLog($dealer_id);
            $last_amount = $log_list = 0;
            $usemoney = $minus_amount;
            $bail_amount = $this->dealer_info['bail_amount']-$minus_amount;
            //判断充值后余额是否大于维保透支
            if($this->dealer_info['bail_amount']<$minus_amount){
                //计算修改状态日志条数
                $log_list = intval($this->dealer_info['bail_amount']/$single_price);
                $last_amount = $minus_amount-($single_price*$log_list);
                $bail_amount = intval(fmod(floatval($this->dealer_info['bail_amount']),$single_price));
            }
            if($last_amount!=0){
                $usemoney = $single_price*$log_list;
            }
            //收银台收款记录
            M()->startTrans();
            $collection_no  = genBillsNo('SK',9);
            $colle_state = AssetCenter::collection_log($collection_no,$usemoney,9);
            $bail = new ThriftBailService();
            $use_type = 8;
            $bail_state = $bail->decBail($this->dealer_id,$usemoney,$use_type,'查询维修保养扣款',0,0,0,$colle_state);
            if($bail_state->code !='000000'){
                M()->rollback();
                return false;
            }
            $bail_log =  AssetCenter::last_bail_log($this->dealer_id,$usemoney,$use_type);//获取最新日志log
            $dealer->edit(array('minus_amount'=>$last_amount)); //修改用户授权额度
            $pay_log->the_bill($usemoney,$bail_log,$colle_state,$log_list);  //结算操作
            M()->commit();
        }
    }

    /**
     * 检测订单状态
     */
    public function check_order_status(){
        $order_no = I('post.order_no');
        //通过返回订单号查询订单信息
        $charge = new Charge();
        $order_info = $charge->getByOrderNo($order_no);
        switch($order_info['pay_result']){
            case 1:
                exit(json_encode(array('code'=>500,'msg'=>"订单已支付")));
                break;
            case 3:
                exit(json_encode(array('code'=>500,'msg'=>"订单支付中")));
                break;
            case 0:
            case 2:
            return $this->api_200();
            break;
        }
    }
}